// 封装http请求接口
var config = require('../config.js');
module.exports = (url, data, isLoading) => { //isLoading
	var isLoading = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
	var method = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'POST';
	var header = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {
		'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
	};
	for (let i in data) {
		if (typeof(data[i]) == 'undefined' || (data[i] != 0 && !data[i])) {
			delete data[i];
		}
	}
	return new Promise(function(resolve, reject) {
		if (isLoading == 1) {
			wx.showLoading({
				title: '正在加载...',
				mask: true
			})
		}
		if (wx.getStorageSync('userInfo').token) {
			header.token = wx.getStorageSync('userInfo').token;
			header.cid = wx.getStorageSync('userInfo').userInfo.id;
		}
		wx.request({
			url: url,
			data: data,
			method: method,
			header: header,
			success: function(res) {
				if (res.statusCode == 401) {
					wx.request({
						url: `${config.host}user/login`,
						data: {
							openid: config.openid
						},
						method: method,
						header: header,
						success(res) {
							if (res.status == 1) {
								config.idFlag = true;
								wx.setStorageSync({
									key: 'userInfo',
									data: res.content
								})
								wx.navigateBack({
									delta: 99
								})
								wx.showToast({
									title: '登录过期，已为您自动登录~'
								})
							} else {
								reject(res.data);
								// 调登录接口失败，说明没有注册，更改id判断值
								config.idFlag = false; //没有注册
								
							}
						}
					})
				} else {
					resolve(res.data);
				}
				if (isLoading == 1) {
					wx.hideLoading();
				}
			},
			fail: function(res) {
				// console.log(res);
				util.wxShowToast('http请求错误！');
				if (isLoading == 1) {
					wx.hideLoading();
				}
			}
		})
	})
}
